import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/networks/course/models/course_response.dart';
import 'package:edu/pages/supplement/%20shopping_cart/shopping_cart_page.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:tuple/tuple.dart';

class CourseTableContentUnit {
  final int id;
  final String title;
  final String? timeString;
  final bool isChapter;
  final bool isFree;

  CourseTableContentUnit({
    required this.id,
    required this.title,
    this.timeString,
    required this.isChapter,
    required this.isFree,
  });
}

class CourseDetailPageLogic extends ChangeNotifier {
  final int _id;

  // 课程详情
  CourseDetail? courseDetail;
  bool isLoading = false;
  bool isError = false;

  bool get isContentEmpty => courseDetail == null; // 课程详情是否为空
  bool get isMycourse =>
      courseDetail?.author.id == AccountInfo.shared.accountId; // 是否是作者
  bool get isPurchased =>
      AccountInfo.shared.purchasedCourses.contains(_id); // 课程是否已购

  int currentTabIndex = 0; // 当前tab索引

  bool _showTitle = false;
  bool get showTitle => _showTitle;

  String? get courseTitle => courseDetail?.title;

  late final mainScrollController = ScrollController();

  List<CourseTableContentUnit> categoryUnits = []; // 课程目录分类

  // 课程评价
  CancelToken? _reviewCancelToken;
  List<CourseReview> reviews = [];
  int? _lastReviewPage;
  int _reviewPage = 1;
  int _reviewPageSize = 20;
  bool isReviewLoading = false;
  bool isReviewError = false;
  bool get isReviewEmpty => reviews.isEmpty;
  bool get canLoadMoreReviews {
    if (_lastReviewPage != null) {
      return _reviewPage <= _lastReviewPage!;
    } else {
      return true;
    }
  }

  int get courseId => _id;
  bool _onBusinessNetwork = false; // 是否正在请求

  //课程收藏
  bool _favoriteChanging = false;
  bool get isMyFavorite => courseDetail?.isFavorite ?? false;

  CourseDetailPageLogic({required int id}) : _id = id;

  void init() {
    mainScrollController.addListener(_scrollListener);

    Future.delayed(Duration.zero, () {
      loadCourseDetail();
    });
  }

  @override
  void dispose() {
    mainScrollController.removeListener(_scrollListener);
    mainScrollController.dispose();
    _reviewCancelToken?.cancel();
    super.dispose();
  }

  // 滚动监听
  void _scrollListener() {
    if (mainScrollController.offset > 80 && !_showTitle) {
      _showTitle = true;
      notifyListeners();
    } else if (_showTitle && mainScrollController.offset <= 80) {
      _showTitle = false;
      notifyListeners();
    }
  }

  // 课程收藏
  void toggleFavorite() async {
    if (_favoriteChanging) {
      return;
    }
    _favoriteChanging = true;

    try {
      if (isMyFavorite) {
        // 取消收藏
        final response = await DataFetcher.shared.businessApi
            .removeFavoriteCourse(_id);
        if (response.code == 0) {
          courseDetail?.isFavorite = false;
          EasyLoading.showSuccess(AppStrings.ddFavoriteCancelSuccess);
          notifyListeners();
        } else {
          if (response.message != null) {
            EasyLoading.showError(
              response.message ?? AppStrings.ddFavoriteCancelError,
            );
          }
        }
      } else {
        // 收藏
        final response = await DataFetcher.shared.businessApi.addFavoriteCourse(
          _id,
        );
        if (response.code == 0) {
          courseDetail?.isFavorite = true;
          EasyLoading.showSuccess(AppStrings.ddFavoriteSuccess);
          notifyListeners();
        } else {
          if (response.message != null) {
            EasyLoading.showError(
              response.message ?? AppStrings.ddFavoriteError,
            );
          }
        }
      }
    } catch (e) {
      log('toggleFavorite error:$e');
    } finally {
      _favoriteChanging = false;
    }
  }

  // 课程添加到购物车
  Future<bool> addToShoppingCarts() async {
    // 课程已购
    if (AccountInfo.shared.purchasedCourses.contains(_id)) {
      EasyLoading.showToast(AppStrings.courseAlreadyPurchased);
      return false;
    }
    // 课程已添加到购物车
    if (AccountInfo.shared.purchasingCourses.contains(_id)) {
      EasyLoading.showToast(AppStrings.courseAlreadyInShoppingCart);
      return false;
    }
    if (_onBusinessNetwork || courseDetail == null) {
      return false;
    }
    _onBusinessNetwork = true;

    try {
      final response = await DataFetcher.shared.businessApi
          .addCourseToShoppingCart(_id, courseDetail!.price);

      if (response.code == 0) {
        EasyLoading.showToast(AppStrings.addToShoppingCartSuccess);
        AccountInfo.shared.addCourseToShoppingCarts(_id);
        return true;
      } else {
        EasyLoading.showError(
          response.message ?? AppStrings.addToShoppingCartError,
        );
        return false;
      }
    } catch (e) {
      log('addToShoppingCart error:$e');
    } finally {
      _onBusinessNetwork = false;
    }

    return false;
  }

  // 课程购买
  void purchase() async {
    if (AccountInfo.shared.purchasedCourses.contains(_id)) {
      EasyLoading.showToast(AppStrings.courseAlreadyPurchased);
      return;
    }

    if (_onBusinessNetwork || courseDetail == null) {
      return;
    }
    _onBusinessNetwork = true;

    try {
      final response = await DataFetcher.shared.businessApi.purchaseCourse([
        _id,
      ]);
      if (response.code == 0 && response.totalPrice != null) {
        EasyLoading.showSuccess(AppStrings.coursePurchased);
        AccountInfo.shared.coursePurchased([_id]);
        ShoppingCartPage.purchasedCourseIdNotifier.value = Tuple2(
          _id,
          response.totalPrice!,
        );
        notifyListeners();
      } else {
        if (response.message != null) {
          EasyLoading.showError(
            response.message ?? AppStrings.coursePurchasedError,
          );
        }
      }
    } catch (e) {
      log('purchase error:$e');
    }
  }

  // 切换tab
  void changeTabIndex(int index) {
    currentTabIndex = index;
    if (index == 2 && reviews.isEmpty) {
      loadReviews();
    }
    notifyListeners();
  }

  // 评价
  void loadReviews() async {
    try {
      if (isReviewLoading) {
        return;
      }
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      isReviewLoading = true;
      isReviewError = false;
      notifyListeners();

      _reviewCancelToken ??= CancelToken();
      final response = await DataFetcher.shared.businessApi.getCourseReviews(
        courseId: _id,
        page: _reviewPage,
        pageSize: _reviewPageSize,
        cancelToken: _reviewCancelToken,
      );
      isReviewLoading = false;
      EasyLoading.dismiss();

      if (response.code == 0) {
        reviews.addAll(response.reviews ?? []);
        _lastReviewPage = response.pageMeta?.lastPage;
        _reviewPage = (response.pageMeta?.currentPage ?? _reviewPage) + 1;
        _reviewPageSize = response.pageMeta?.pageSize ?? 20;
      } else {
        isReviewError = true;
        EasyLoading.showError(response.message ?? AppStrings.reviewError);
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      if (e.type == DioExceptionType.cancel) {
        return;
      }
      isReviewError = true;
      isReviewLoading = false;
      notifyListeners();
      log('Error:$e');
    } catch (e) {
      rethrow;
    } finally {
      _reviewCancelToken?.cancel();
      _reviewCancelToken = null;
      notifyListeners();
    }
  }

  // 加载课程详情
  void loadCourseDetail() async {
    try {
      if (isLoading) return;

      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      isLoading = true;
      isError = false;
      notifyListeners();

      final response = await DataFetcher.shared.courseApi.getCourseDetail(_id);
      EasyLoading.dismiss();
      isLoading = false;

      if (response.code == 0) {
        courseDetail = response.course;
        isError = false;
        _makeCategoryUnits();
      } else {
        isError = true;
        EasyLoading.showError(response.message ?? AppStrings.courseDetailError);
      }
      notifyListeners();
    } catch (e) {
      isLoading = false;
      isError = true;
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      notifyListeners();
    }
  }

  void _makeCategoryUnits() {
    // 构建目录分类
    final chapters = courseDetail?.chapters;
    if (chapters == null) {
      return;
    }
    categoryUnits.clear(); // 清空

    var chapterIndex = 0;
    for (final chapter in chapters) {
      // 章节---第几章 xxxx
      final chapterTitle =
          '${AppStrings.chapterIndex(chapter.index)} ${chapter.title}';

      categoryUnits.add(
        CourseTableContentUnit(
          id: chapter.id,
          title: chapterTitle,
          isChapter: true,
          isFree: false,
        ),
      );

      // 视频-- xxxxx(00:00)
      for (final item in chapter.videos ?? []) {
        final cIndex = chapter.index; // 章节索引
        final vIndex = item.index; // 视频索引
        final vTitle = item.title; // 视频标题
        final vMinutes = item.duration ~/ 60; // 分钟
        final vSeconds = (item.duration % 60).toString().padLeft(2, '0'); // 秒
        final videoTitle = '$cIndex-$vIndex $vTitle';
        final timeString = '($vMinutes:$vSeconds)';

        categoryUnits.add(
          CourseTableContentUnit(
            id: item.id,
            title: videoTitle,
            timeString: timeString,
            isChapter: false,
            isFree: chapterIndex++ < 2,
          ),
        );
      }
    }
  }
}
